import {Component, ViewChild} from '@angular/core';
import {Content, InfiniteScroll, IonicPage, NavController, PopoverController} from 'ionic-angular';
import {PagingConfig} from "@providers/paging";
import {DialogProvider} from "@providers/dialog";
import {StorageProvider} from "@providers/storage";
import {WorkerProvider} from "@providers/interface/worker";
import {env} from "@env/environment";

@IonicPage()
@Component({
  selector: 'page-worker-materiel',
  templateUrl: 'worker-materiel.html',
})
export class WorkerMaterielPage {
  @ViewChild('tel') tel: any;
  @ViewChild(Content) content: Content;
  userInfo: any;
  datas: any[] = [];
  datasConfig: PagingConfig = new PagingConfig();
  isScrollDown = false;//判断页面是否是向下滑动
  canclick: any;
  STATUS_ID: any;

  dev:boolean;

  constructor(private dialog: DialogProvider,
              private worker: WorkerProvider,
              public navCtrl: NavController,
              private storageService: StorageProvider,
              private popoverCtrl: PopoverController,) {
    this.userInfo = this.storageService.read("userInfo");
    console.info(this.userInfo);
    this.dev = env.mode == "prod";
  }

  push(page: string, data?: any) {
    if (data) {
      if (data["SP"]) {
        data["SP"] = data.CSM_SORDERITEM[0];
      }
      this.navCtrl.push(page, data);
    } else {
      this.navCtrl.push(page);
    }
  }

  ionViewWillEnter() {
    this.userInfo = this.storageService.read("userInfo");
    this.datas = [];
    this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
      this.datas.forEach((v) => {
        this.calculateSum(v);
      });
    }, this.datasConfig);
    if (this.userInfo.SFZX != '0') {
      this.content.getScrollElement().style["margin-top"]='137px';
    } else {
      this.content.getScrollElement().style["margin-top"]='45px';
    }
  }

  details(page, data) {
    this.navCtrl.push(page, data);
  }

  /**
   * 滑动时触发
   */
  scrollContent() {
    this.isScrollDown = this.content.directionY == "down";
  }

  /**
   * 刷新数据
   */
  refresh(refresher?: any) {
    this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
      this.datas.forEach((v) => {
        this.calculateSum(v);
      });
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
      console.log(this.datas);
    }, this.datasConfig, error => {
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    });
  }

  /**
   * 确认收货
   */
  sumbit(data) {
    console.info(data);
    this.dialog.showConfirm(() => {
      this.worker.confirmReceipt({
        ORDER_ID: data.ORDER_ID,
        PARTYID: this.userInfo.PARTYID,
        NAME: this.userInfo.USERNAME
      }).then(v => {
        console.log(v, '收货成功');
        //this.STATUS_ID='YCL'
        this.refresh();
        console.info(data);
      }).catch(e => {
        this.dialog.showAlert('收货失败');
        console.info(e)
      });
    }, "确认收货")
  }

  /**
   * 下滑数据获取
   * @param infiniteScroll
   */

  getMoreDatas(infiniteScroll: InfiniteScroll) {
    this.getData((value) => {
      value.forEach((v) => {
        this.calculateSum(v);
      });
      this.datas.push.apply(this.datas, value);

      infiniteScroll.complete();
    }, this.datasConfig);
  }

  /**
   * STATUS_ID,'OrderOpen','创建','OrderProcessing','发货','OrderCompleted','收货','OrderCancelled','作废'
   * 获取数据
   * @param pagingConfig 分页
   * @param fn 方法
   * @param errorFun 方法
   */
  getData(fn: (value) => void, pagingConfig, errorFun?: (error) => void) {
    this.worker.getPartsInfo(
      {partyId: this.userInfo.PARTYID},
      pagingConfig
    ).then(v => {
      console.info(this.userInfo.SFZX);
      fn(v);
      v.forEach((v) => {
        //console.info( v.STATUS_ID =='OrderCompleted')
        if (v.STATUS_ID == "OrderProcessing") {
          return v.canclick = true;
        } else {
          return v.canclick = false;
        }
      });
      console.log(v)
    }).catch(e => {
      if (errorFun) {
        errorFun(e);
      }
    });
  }

  /**
   * 计算费用列表合集
   */
  calculateSum(data?: any) {
    let sum = 0;
    for (let i = 0; i < data.materialCosts.length; i++) {
      let value = data.materialCosts[i];
      sum += value.PRICE * value.QUANTITY;
    }
    data["sum"] = Math.floor(sum * 100) / 100;
  }

  /**
   * 开工
   */
  switchIsWorking() {
    this.worker.switchIsWorking(this.userInfo["PARTYID"], '10').then(v => {
      this.userInfo.SFZX = v.data["SFZX"];
      this.storageService.write('userInfo', this.userInfo);
    }).then(() => {
      this.content.getScrollElement().style["margin-top"]='137px';
      // document.getElementsByClassName("scroll-content")[2].setAttribute('style', 'margin-top:137px;');
      // document.getElementsByClassName("fixed-content")[2].setAttribute('style', 'margin-top:137px;');
    }).catch(e => {
    });
  }

  pop(myEvent,page){
    let popover = this.popoverCtrl.create(page, {}, {cssClass: 'sum'});
    popover.onDidDismiss(data => {
      this.refresh()
    });
    popover.present({
      ev: myEvent
    });

  }

}
